package com.xxl.sso.core.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName RequestUtils
 * @Description 获取请求域名
 * @Author wangke
 * @Date 2022/1/25 14:33
 */
@Slf4j
public class RequestUtils {

    /* 正则匹配IP */
    public static String PATTERN_IP = "(\\d*\\.){3}\\d*";

    public static String getDomain(HttpServletRequest request){
        StringBuffer url = request.getRequestURL();
        log.info("##########RequestUtils getDomain url:{}",url);
        String domain = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
        log.info("##########RequestUtils getDomain domain:{}",domain);
        return domain;
    }

    public static String getDomainMatchIp(String url) {
            /* 以IP形式访问时，返回IP */
            Pattern ipPattern = Pattern.compile(PATTERN_IP);
            Matcher matcher = ipPattern.matcher(url);
            if (matcher.find()) {
                log.info("##########RequestUtils getDomainFromIp match ip");
                return matcher.group();
            }else{
                return null;
            }
    }
}
